package com.zhiqian.community.controller;

import com.zhiqian.community.entity.Event;
import com.zhiqian.community.event.EventProducer;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/share")
public class ShareController implements CommunityConstant {

    private static final Logger logger= LoggerFactory.getLogger(ShareController.class);
    @Autowired
    private EventProducer eventProducer;

    @Value("${wk.image.storage}")
    private String imagesStorage;

    /**
     * 分享
     * @param htmlUrl
     * @return
     */
    @GetMapping("/createImage")
    @ResponseBody
    public String share(String htmlUrl){
        String fileName = CommunityUtil.generateUUID();
        Event event=getShareEvent(htmlUrl,fileName);
        //以异步的方式生成长图
        eventProducer.fireEvent(event);
        //返回访问路径
        Map<String, Object> map = new HashMap<>();
        map.put("shareUrl",fileName);
        return CommunityUtil.getJSONString(0,map);
    }

    /**
     * 获取长图
     * @param fileName
     * @param response
     */
    @GetMapping("/image/{fileName}")
    public void getShareImage(@PathVariable("fileName")String fileName, HttpServletResponse response){
        if (StringUtils.isBlank(fileName)){
            throw new IllegalArgumentException("文件名不能为空");
        }
        String filePath = imagesStorage+"/"+fileName+".png";
        response.setContentType("image/png");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".png");
        File file=new File(filePath);
        while (!file.exists()){
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            logger.error("等待生成长图时出现异常："+e.getMessage());
        }
        try(
                FileInputStream fileInputStream = new FileInputStream(file);
                BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        ){
            response.setHeader("Content-Length",String.valueOf(fileInputStream.available()));
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, b);
            }
            logger.info(String.format("读取长图成功！[%s]",fileName));
        }catch (IOException e){
            logger.error("读取长图失败!"+e.getMessage());
        }

    }

    private Event getShareEvent(String htmlUrl, String fileName) {
        Event event=new Event();
        event.setTopic(TOPIC_SHARE);
        event.setData("htmlUrl",htmlUrl);
        event.setData("fileName",fileName);
        event.setData("suffix",".png");
        return event;
    }

}
